<template>
<div>
    <mt-header class="plain" title="账号与安全">
        <mt-button :icon="editable ? '' : 'back'" slot="left" @click="goBack">{{editable ? '取消' : '返回'}}</mt-button>
        <mt-button slot="right" @click="complete">{{editable ? '完成' : '编辑'}}</mt-button>
    </mt-header>

    <div class="info-container">

        <div class="info-avatar">
            <img :src="userAvatar || userInfo.avatarUrl || img.myAvatar" @click="editable && changeAvatar($event)">
            <form action="javascript:;" ref="avatarFileForm">
                <input type="file" ref="avatarFile" v-show="false" @change="handleAvatarFileChange" accept="image/*">
            </form>
        </div>

        <div class="option-item">
            <mt-cell title="昵称" :value="userInfo.username" class="spec color-secondary" v-show="!editable"></mt-cell>
            <mt-field label="昵称" v-model="userInfo.username" class="spec color-secondary right-input" v-show="editable"></mt-field>
        </div>
        <div class="option-item">
            <mt-cell title="真实姓名" :value="userInfo.realName" class="spec color-secondary"></mt-cell>
        </div>
        <div class="option-item">
            <mt-cell title="身份证号" :value="userInfo.idCardNo" class="spec color-secondary"></mt-cell>
        </div>
        <div class="option-item">
            <mt-cell title="手机号码" :value="userInfo.phoneNo" class="spec color-secondary"></mt-cell>
        </div>
        <!-- <div class="option-item">
                <mt-cell title="电子邮箱" :value="userInfo.email" class="spec color-secondary" v-show="!editable"></mt-cell>
                <mt-field label="电子邮箱" v-model="userInfo.email" class="spec color-secondary" v-show="editable"></mt-field>
            </div> -->
        <div class="option-item" @click="!editable && goChangePasswordPage($event)">
            <mt-cell title="更改密码" class="spec" is-link></mt-cell>
        </div>
        <div class="option-item" @click="!editable && goCompletePage($event)">
            <mt-cell title="完善详细资料" class="spec" is-link></mt-cell>
        </div>

        <div class="info-button">
            <mt-button type="primary" style="width: 160px; height: 45px;" @click="logout" v-show="!editable">退出登录</mt-button>
        </div>
    </div>
</div>
</template>

<script>
import myAvatarImg from '@/assets/images/personal/个人中心_完善资料_头像.png'

import {
    MessageBox
} from 'mint-ui'
import {
    Toast
} from 'mint-ui'
import {
    Const
} from '@/consts'
import utils from '@/utils'
import fileApi from '@/api/file'
import userApi from '@/api/user'

export default {
    data() {
        return {
            img: {
                myAvatar: myAvatarImg
            },
            userInfo: {},
            editInfo: {},
            userAvatar: '',
            userAvatarId: '',
            editable: false
        }
    },

    created() {
        // this.userInfo = utils.get('USER_INFO') || {};
        this.getUserInfo()
    },

    methods: {

        clearFileStatus() {
            this.userAvatar = ''
            this.userAvatarId = ''
        },

        goBack() {

            if (this.editable) {
                this.editable = false
                this.clearFileStatus()
                this.getUserInfo()
                return
            }

            let from = this.$route.query.from || '';

            if (from) {
                this.$router.replace('/' + from.replace(/-/g, '/'));
            } else {
                this.$router.replace('/personal/setting')
            }
        },

        formValidate(field) {
            return true;
        },

        complete() {
            if (!this.editable) {
                this.editable = true
                return
            }

            if (!this.formValidate()) {
                return
            }

            this.editable = false
            userApi.modifyBaseInfo2({
                params: {
                    username: this.userInfo.username,
                    email: this.userInfo.email,
                    avatarid: this.userAvatarId || this.userInfo.avatarId
                }
            }).then((resp) => {
                Toast(resp[Const.RESP_MESSAGE] || '修改成功');
                this.clearFileStatus()
                this.getUserInfo()
            }).catch((resp) => {
                // Toast(resp[Const.RESP_MESSAGE] || '修改失败');
                this.editable = true
                if (resp.statusCode == '200') {
                    Toast(resp[Const.RESP_MESSAGE] || '修改失败');
                }
            });
        },

        goChangePasswordPage() {
            this.$router.push('/personal/setting/password/change')
        },

        goCompletePage() {

            const msgText = '<div class="text-justify" style="line-height: 25px;">该信息将用于在通过考试后、报考学校时生成纸质报名表，若信息不符可能导致报名失败，请您依照真实情况填写。<div>'

            MessageBox.confirm(msgText, '温馨提示', {
                confirmButtonText: '我已知晓',
                cancelButtonText: '我要再考虑一下',
                closeOnClickModal: false,
                type: 'info'
            }).then(action => {
                //
                this.$router.push('/personal/setting/complete')
            }).catch(() => {

            })
        },

        logout() {

            MessageBox.confirm('您确定要退出吗？', '确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'info'
            }).then(action => {
                //
                utils.clearUserInfo();
                this.$router.replace('/login');
            }).catch(() => {

            })
        },

        getUserInfo() {
            userApi.getUserInfo().then((resp) => {
                const result = resp[Const.RESP_RESULT] || {};
                this.userInfo = {
                    username: result.username,
                    phoneNo: result.phoneno,
                    email: result.email,
                    realName: result.realname,
                    idCardNo: result.idcardno,
                    avatarUrl: result.avatarurl,
                    avatarId: result.avatarid,
                    lastLoginTime: result.lastlogintime
                };

                utils.save('USER_INFO', this.userInfo);
            }).catch((resp) => {
                // Toast(resp[Const.RESP_MESSAGE]);
            });
        },

        changeAvatar() {
            this.$refs.avatarFile.click();
        },

        handleAvatarFileChange() {
            let file = this.$refs.avatarFile.files[0]

            if (!file) {
                return;
            }

            this.$refs.avatarFileForm.reset()
            fileApi.upload({
                params: {
                    file: file
                }
            }).then(resp => {
                let result = resp[Const.RESP_RESULT] || ''
                this.userAvatarId = result.id || result.objectid || result.url || result || ''
                this.userAvatar = result.url || result || ''
                Toast('上传成功')
            }).catch(resp => {
                if (resp.statusCode == '200') {
                    Toast(resp[Const.RESP_MESSAGE] || '出错了 ...')
                }
            })

            // this.userAvatarFile = file

            // let reader = new FileReader()

            // reader.onload = ($e) => {
            //     this.userAvatar = $e.target.result
            // }

            // reader.readAsDataURL(file)
            // reader = null

            // userApi.modifyBaseInfo({
            //     params: {
            //         avatarfile: file
            //     }
            // }).then((resp) => {
            //     this.getUserInfo();
            // }).catch((resp) => {
            //     // Toast(resp[Const.RESP_MESSAGE] || '修改失败');
            // });
        }
    }
}
</script>

<style lang="scss" scoped>
$offset-x: 16px;
$scale: 1.2;
.info-container {
    margin-left: $offset-x;
    margin-right: $offset-x;
    border-top: 1px solid #dddddd;
    .info-avatar {
        margin: 24px 0 18px 0;
        img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
        }
    }
    .option-item {
        height: 48px;
        border-bottom: 1px solid #dddddd;
        font-size: 14px * $scale;
        text-align: left;
        .spec {
            color: #333333;
        }
    }
    .info-button {
        margin: 56px 0;
    }
}

</style>
